package com.bclz.controller;

import java.io.Serializable;
import java.time.Clock;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bclz.bo.CommentBo;
import com.bclz.bo.PageBo;
import com.bclz.common.FileService;
import com.bclz.common.WxService;
import com.bclz.common.constant.WebConstants;
import com.bclz.common.response.ResponseData;
import com.bclz.common.response.ResponseUtils;
import com.bclz.entity.User;
import com.bclz.service.UserService;
import com.bclz.util.EntityHelper;
import com.github.pagehelper.PageInfo;

import ch.qos.logback.classic.Logger;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;

/**
 * 
* Title: UserController  
* Description:   用户Handle
* @author xuchang  
* @date 2018年8月9日
 */
@RestController
@RequestMapping("/user")
public class UserController {
		
	
	private Logger log=(Logger)LoggerFactory.getLogger(getClass());
	
	@Autowired
	private RedisTemplate<String, Serializable> redisTemplate;
	
	@Autowired
	private WxService wxService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private FileService fileService;
	
	
	/**
	 * 
	 * Title: signin  
	 * Description:  微信登陆，1.解密用户信息，2.生成登陆skey存入redis作为标识
	 * @param code
	 * @param encrypteData
	 * @param iv
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ApiOperation(value="微信登陆小程序", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "微信端临时登录code值", required = true, dataType = "String"),
		@ApiImplicitParam(name = "encrypteData", value = "包括敏感数据在内的完整用户信息的加密数据", required = true, dataType = "String"),
		@ApiImplicitParam(name = "iv", value = "加密算法的初始向量", required = true, dataType = "String")}
	)
	public ResponseData signin(
            @RequestParam(value = "code",required = true) String code,
//            @RequestParam(value = "rawData",required = false) String rawData,
//            @RequestParam(value = "signature",required = false) String signature,
            @RequestParam(value = "encrypteData",required = true) String encrypteData,
            @RequestParam(value = "iv",required = true) String iv) {
		if(code==null || encrypteData==null || iv==null) {
			return ResponseUtils.fail("参数异常", null);
		}
		
//		log.info("用户非敏感信息:{}",rawData);
//		JSONObject rawDataJson =JSONObject.fromObject(rawData);
		
//		log.info("签名:{}",signature);
		
		JSONObject SessionKeyOpenId =wxService.getSessionKeyOropenid(code);
		log.info("SessionAndopenId=:{}",SessionKeyOpenId);
		//获取openid
		String openid=SessionKeyOpenId.getString("openid");
		log.info("openid=:{}",openid);
		//获取sessionKey
		String sessionKey = SessionKeyOpenId.getString( "session_key" );
		log.info("sessionKey=:{}",sessionKey);
		
		User u=userService.getbyOpenid(openid);
		JSONObject encrypteDataJson= wxService.getUserInfo(encrypteData, sessionKey, iv);
		log.info("encrypte=:{}",encrypteDataJson);
		if(u==null) {
			
			String nickName = encrypteDataJson.getString( "nickName" );
	        String avatarUrl = encrypteDataJson.getString( "avatarUrl" );
	        Integer gender  = encrypteDataJson.getInt( "gender" );
	        String city = encrypteDataJson.getString( "city" );
	        String country = encrypteDataJson.getString( "country" );
	        String province = encrypteDataJson.getString( "province" );
	        try {
	        	avatarUrl=fileService.fromNetImage(avatarUrl,openid);
	        }catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("远程获取头像异常 {}",e);
				return ResponseUtils.fail("远程获取头像异常", null);
			}
	        
			u=new User();
			u.setStatus(1);
			u.setOpenid(openid);
			u.setName(nickName);
			u.setAvatar(avatarUrl);
			u.setGender(gender==1?"男":"女");
			u.setAddress((country==null?"":country)+(province==null?"":province)+(city==null?"":city));
			try {
				userService.add(u);
			}catch(Exception e) {
				log.error("添加用户出错  openid:{} nickname:{}", openid,nickName,e);
				return ResponseUtils.fail("登录失败，服务器异常", null);
			}
			
		}
		String redis_skey=(String)redisTemplate.opsForValue().get("openkey:"+openid);
		if(StringUtils.isNotBlank(redis_skey)) {
			redisTemplate.delete(redis_skey);
		}
		//uuid生成唯一key
	    String skey = UUID.randomUUID().toString()+Clock.systemDefaultZone().millis();
	    redisTemplate.opsForValue().set("openkey:"+openid, skey);
	    redisTemplate.opsForValue().set(skey, openid+":"+sessionKey,30,TimeUnit.MINUTES);
	    Map<String,Object> result=new HashMap<>();
	    result.put("userInfo", u);
	    result.put("openid", openid);
	    result.put("skey", skey);
		return ResponseUtils.success("登录成功", result);
	}
	
	/**
	 * 
	 * Title: getUser  
	 * Description:  查询用户信息
	 * @param openid
	 * @return
	 */
	@ApiOperation(value="查询用户信息", notes="根据用户openid查询用户信息")
	@ApiImplicitParam(name = "openid", value = "微信openid", required = true, dataType = "String")
	@RequestMapping(value="/info/{openid}",method=RequestMethod.GET)
	public ResponseData getUser(@PathVariable(value="openid") String openid) {
		
		User u=userService.getbyOpenid(openid);
		return ResponseUtils.success("查询成功", u);
	}
	
	
	/**
	 * 
	 * Title: selfInfo  
	 * Description:  更新保存用户信息，图片文件名对比
	 * @param u
	 * @param req
	 * @return
	 */
	@ApiOperation(value="保存用户信息", notes="更新保存用户信息，图片文件名对比")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "aboutme", value = "个人简介", required = false, dataType = "String"),
		@ApiImplicitParam(name = "address", value = "地址", required = false, dataType = "String"),
		@ApiImplicitParam(name = "avatar", value = "图片路径", required = false, dataType = "String"),
		@ApiImplicitParam(name = "avatarFile", value = "图片文件", required = false, dataType = "MultipartFile"),
		@ApiImplicitParam(name = "gender", value = "性别", required = true, dataType = "String"),
		@ApiImplicitParam(name = "name", value = "昵称", required = true, dataType = "String"),
		@ApiImplicitParam(name = "openid", value = "用户openid", required = true, dataType = "String"),
		@ApiImplicitParam(name = "phone", value = "手机号码", required = false, dataType = "String")}
	)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public ResponseData selfInfo(User u) {
		
		ResponseData resu=EntityHelper.validateUser(u);
		if(resu.getCode()==WebConstants.FAIL_CODE) {
			return resu;
		}
		u=(User)resu.getData();
		u.setAvatar(null);
		if(u.getAvatarFile()!=null) {
			if(!fileService.fileExists(u.getAvatarFile().getOriginalFilename())) {
				try {
					String avatars=fileService.getImagePath(u.getAvatarFile(),u.getOpenid());
					u.setAvatar(avatars);
				}catch (Exception e) {
					// TODO Auto-generated catch block
					log.error("文件保存出错 {}", e.getMessage());
				}
				
			}
		}
		
		try {
			u.setStatus(0);
			int num= userService.update(u);
			return num==0?ResponseUtils.fail("更新失败，服务器内部错误，请稍后重试", null):ResponseUtils.success("保存成功", null);
		}catch(Exception e) {
			log.error("更新用户信息失败", e);
			return ResponseUtils.fail("更新失败，服务器内部错误，请稍后重试", null);
		}
		
	}
	
	/**
	 * 
	 * Title: selflistComment  
	 * Description:  我的评论
	 * @param id
	 * @return
	 */
	@ApiOperation(value="用户已经评论列表", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
		@ApiImplicitParam(name = "pageNum", value = "当前页", required = false, dataType = "Integer"),
		@ApiImplicitParam(name = "pageSize", value = "每页的数量", required = false, dataType = "Integer")}
	)
	@RequestMapping(value="/comment/{userId}",method=RequestMethod.GET)
	public ResponseData selflistComment(@PathVariable("userId") String userId,PageBo page) {
		
		PageInfo<CommentBo> commentList=userService.selflistComment(userId,page);
		return ResponseUtils.success("查询成功", commentList);
	}
	
	
	/**
	 * 
	 * Title: selflistResponse  
	 * Description:  回复我的
	 * @param id
	 * @return
	 */
	@ApiOperation(value="回复用户列表", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
		@ApiImplicitParam(name = "pageNum", value = "当前页", required = false, dataType = "Integer"),
		@ApiImplicitParam(name = "pageSize", value = "每页的数量", required = false, dataType = "Integer")}
	)
	@RequestMapping(value="/response/{userId}",method=RequestMethod.GET)
	public ResponseData selflistResponse(@PathVariable("userId")String userId,PageBo page) {
		PageInfo<CommentBo> commentList=userService.selflistResponse(userId,page);
		return ResponseUtils.success("查询成功", commentList);
	}
	
	
}
